package com.locationtracker.plus.app.util

import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.blankj.utilcode.util.NotificationUtils
import com.locationtracker.plus.BuildConfig
import com.locationtracker.plus.R
import com.locationtracker.plus.ui.activity.MainActivity

class LocationForegroundService : Service() {

    override fun onBind(intent: Intent): IBinder? {
        throw UnsupportedOperationException("Not yet implemented")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (ACTION_STOP == intent?.action) {
            stopForeground(true)
        } else if (ACTION_START == intent?.action) {
            startForeground(
                applicationInfo.uid,
                NotificationUtils.getNotification(
                    NotificationUtils.ChannelConfig(
                        packageName,
                        packageName,
                        NotificationUtils.IMPORTANCE_MIN
                    )
                ) {
                    it.setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText("Geolocation detection running.")
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setVibrate(null)
                        .setSound(null)
                        .setLights(0, 0, 0)
                        .setContentIntent(
                            PendingIntent.getActivity(
                                this,
                                0,
                                Intent(this, MainActivity::class.java),
                                PendingIntent.FLAG_IMMUTABLE
                            )
                        )
                        .setAutoCancel(false)
                })
        }
        return START_STICKY
    }

    companion object {
        private const val ACTION_START = "${BuildConfig.APPLICATION_ID}.action.ENABLE"
        private const val ACTION_STOP = "${BuildConfig.APPLICATION_ID}.action.DISABLE"

        fun startService(context: Context) {
            val intent = Intent(context, LocationForegroundService::class.java)
            intent.action = ACTION_START
            context.startService(intent)
        }

        fun stopService(context: Context) {
            val intent = Intent(context, LocationForegroundService::class.java)
            intent.action = ACTION_STOP
            context.startService(intent)
        }
    }
}